package com.gao.wechat.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.gao.wechat.service.WechantMessageService;
import com.gao.wechat.util.HttpUtil;

import net.sf.json.JSONObject;

@Service
public class WechantMessageServiceImpl implements WechantMessageService
{

	private static final Logger logger = LoggerFactory.getLogger(WechantMessageServiceImpl.class);
	
	public String getAccessToken(String appId, String secret) 
	{
		try 
		{
			String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId +"&secret="+ secret;
		    String json = HttpUtil.get(requestUrl);
		    JSONObject jsonObject = JSONObject.fromObject(json);
		    if (jsonObject == null)
		    {
		    	logger.error("获取accessToken失败");
                return null;
            }
		    String access_token = jsonObject.getString("access_token");
		    return access_token;
		}catch(Exception ex) 
		{
			logger.error(ex.getMessage(), ex);
		}
		return null;
	}
	
	@Override
	public void sendCustom(String accessToken, String data) 
	{
		try {
            // 拼接请求地址
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
            // 需要提交的json数据
            String json = HttpUtil.post(requestUrl,data);
            JSONObject jsonObject = JSONObject.fromObject(json);
            if (jsonObject == null) {
                return;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
	}

}
